package org.ucas.faker.web.service.Visualization.json;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jboss.jandex.ClassType;

import java.util.ArrayList;
import java.util.List;

public class JsonUtil {

    public static <T> T getValue(JSONObject json, String keyPath){
        if (keyPath == null) return null;
        String[] keyArray = keyPath.split("\\.");
        int length = keyArray.length;
        JSONObject currentJson = json;

        for (int i=0;i<length-1;i++){
            if (!currentJson.containsKey(keyArray[i])){
                return null;
            } else {
                Object tmp = currentJson.get(keyArray[i]);
                if (tmp instanceof JSONObject){
                    currentJson = currentJson.getJSONObject(keyArray[i]);
                } else {
                    return null;
                }
            }
        }

        if (!currentJson.containsKey(keyArray[length-1])){
            return null;
        } else{
            return (T)currentJson.get(keyArray[length-1]);
        }
    }

    public static boolean containsKey(JSONObject json, String keyPath){
        if (keyPath == null) return false;
        String[] keyArray = keyPath.split("\\.");
        int length = keyArray.length;
        JSONObject currentJson = json;

        for (int i=0;i<length-1;i++){
            if (!currentJson.containsKey(keyArray[i])){
                return false;
            }
            currentJson = currentJson.getJSONObject(keyArray[i]);
        }
        if (currentJson.containsKey(keyArray[length-1])) {
            return true;
        } else {
            return false;
        }
    }

    public static <T> void addElement(JSONObject json, String keyPath, T value){
        if (keyPath == null) return;
        String[] keyArray = keyPath.split("\\.");
        int length = keyArray.length;

        JSONObject currentJson = json;
        for (int i=0;i<length-1;i++){
            JSONObject tmpJson = new JSONObject();
            if (currentJson.containsKey(keyArray[i])){
                tmpJson = currentJson.getJSONObject(keyArray[i]);
            }
            currentJson.put(keyArray[i], tmpJson);
            currentJson = tmpJson;
        }
        currentJson.put(keyArray[length-1], value);
    }

    public static <T> JSONArray listToJsonArray(List<T> list){
        if (list == null){
            return null;
        }
        JSONArray jsonArray = new JSONArray();
        for (T element : list){
            jsonArray.add(element);
        }
        return jsonArray;
    }

    public static <T> JSONArray arrayToJsonArray(T[] array){
        if (array == null){
            return null;
        }
        JSONArray jsonArray = new JSONArray();
        for (T element : array){
            jsonArray.add(element);
        }
        return jsonArray;
    }

    public static <T> JSONArray addElementToJsonArray(JSONArray jsonArray, T element, int index){
        JSONArray resultArray = new JSONArray();
        int p = 0;
        int length = jsonArray.size();
        while (p<length){
            if (p==index){
                resultArray.add(element);
            }
            resultArray.add(jsonArray.get(p));
            p ++;
        }
        return resultArray;
    }

    public static <T> List<T> jsonArrayToList(JSONArray jsonArray){
        if (jsonArray == null){
            return null;
        }
        List<T> list = new ArrayList<T>();
        for (int i=0;i<jsonArray.size();i++){
            list.add((T)jsonArray.get(i));
        }
        return list;
    }

    /**
     * 对json字符串格式化输出
     * @param jsonStr
     * @return
     */
    public static String formatJson(String jsonStr) {
        if (null == jsonStr || "".equals(jsonStr)) return "";
        StringBuilder sb = new StringBuilder();
        char last = '\0';
        char current = '\0';
        int indent = 0;
        boolean inString = false;
        for (int i = 0; i < jsonStr.length(); i++) {
            last = current;
            current = jsonStr.charAt(i);

            if (current == '"' && last != '\\'){
                inString = !inString;
            }
            if (inString) {
                sb.append(current);
                continue;
            }
            switch (current) {
                case '{':
                case '[':
                    sb.append(current);
                    sb.append('\n');
                    indent++;
                    addIndentBlank(sb, indent);
                    break;
                case '}':
                case ']':
                    sb.append('\n');
                    indent--;
                    addIndentBlank(sb, indent);
                    sb.append(current);
                    break;
                case ',':
                    sb.append(current);
                    if (last != '\\') {
                        sb.append('\n');
                        addIndentBlank(sb, indent);
                    }
                    break;
                default:
                    sb.append(current);
            }
        }

        String currentString = sb.toString();
        /*//去掉formatter后面的函数引号
        String resultString = "";
        String[] splitArray = currentString.split("\n");
        for (int i=0;i<splitArray.length;i++){
            if (splitArray[i].indexOf("formatter:\"")!=-1){
                System.out.println("--------------- "+splitArray[i]);
                splitArray[i] = splitArray[i].replace("\"", "");
                System.out.println("+++++++++++++++ "+splitArray[i]);
            }
            resultString += splitArray[i]+"\n";
        }
        currentString = resultString;*/
        return currentString;

    }

    /**
     * 添加space
     * @param sb
     * @param indent
     */
    private static void addIndentBlank(StringBuilder sb, int indent) {
        for (int i = 0; i < indent; i++) {
            sb.append('\t');
        }
    }
}
